package cn.weforward.task.impl;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.weforward.common.ResultPage;
import cn.weforward.common.util.ResultPageHelper;
import cn.weforward.data.UniteId;
import cn.weforward.data.counter.CounterFactory;
import cn.weforward.data.log.BusinessLog;
import cn.weforward.data.log.BusinessLogger;
import cn.weforward.data.log.BusinessLoggerFactory;
import cn.weforward.data.persister.Persistent;
import cn.weforward.data.persister.Persister;
import cn.weforward.data.persister.PersisterFactory;
import cn.weforward.data.persister.ext.ConditionUtil;
import cn.weforward.framework.WeforwardSession;
import cn.weforward.protocol.ops.User;
import cn.weforward.task.Bug;
import cn.weforward.task.Task;
import cn.weforward.task.di.TaskDi;

public class TaskDiImpl implements TaskDi{
	
	protected Persister<SimpleTag> m_PsTag;
	protected Persister<SimpleTask> m_PsTask;
	protected Persister<SimpleBug> m_PsBug;
	protected PersisterFactory m_Factory;
	/**记录任务日志 **/
	protected BusinessLogger m_TaskLogger;
	
	public TaskDiImpl(PersisterFactory factory,BusinessLoggerFactory loggerFactory) {
		// TODO Auto-generated constructor stub
		m_Factory = factory;
		m_PsTag = factory.createPersister(SimpleTag.class, this);
		m_PsTask = factory.createPersister(SimpleTask.class, this);
		m_PsBug = factory.createPersister(SimpleBug.class, this);
		m_TaskLogger = loggerFactory.createLogger("task_log");
	}
	
	@Override
	public <E extends Persistent> Persister<E> getPersister(Class<E> clazz) {
		// TODO Auto-generated method stub
		return m_Factory.getPersister(clazz);
	}
	

	//传入标签id,和数据库中的每个任务中的m_Tag属性比较
	@Override
	public ResultPage<SimpleTask> searchTasks(String tagId) {
		ResultPage<SimpleTask> rp = m_PsTask.search(ConditionUtil.eq(ConditionUtil.field("m_Tag"), tagId));
		List<Task> list = new ArrayList<>();
		for (SimpleTask simpleTask : ResultPageHelper.toForeach(rp)) {
			//如果任务为父任务
			if("".equals(simpleTask.getFatherTaskId())) {
				list.add(simpleTask);
			}
		}
		
		return ResultPageHelper.toResultPage(list);
	}

	@Override
	public ResultPage<BusinessLog> getLogs(UniteId id) {
		return m_TaskLogger.getLogs(id.getId());
	}
	
	@Override
	public void writeLog(UniteId id, String action, String what, String note) {
		// TODO Auto-generated method stub
		User user = WeforwardSession.TLS.getOperator();
		String author = null == user ? "system" : user.getName();
		m_TaskLogger.writeLog(id.getId(), author, action, what, note);
	}

	@Override
	public ResultPage<SimpleTask> getSonTasks(String fatherId) {
		// TODO Auto-generated method stub
		ResultPage<SimpleTask> rp = m_PsTask.search(ConditionUtil.eq(ConditionUtil.field("m_FatherTaskId"), fatherId));
		return rp;
	}

	@Override
	public Bug createBug(String content, String taskId, List<String> handler, String severity, String versionAndPlatForm) {
		
		return new SimpleBug(this, content, taskId, handler, severity, versionAndPlatForm);
		
	}

	@Override
	public ResultPage<SimpleBug> getAllBugs(String taskId) {
		// TODO Auto-generated method stub
		ResultPage<SimpleBug> rp = m_PsBug.search(ConditionUtil.eq(ConditionUtil.field("m_TaskId"), taskId));
		return rp;
	}
	@Override
	public HashMap<String, Integer> analyzeBugs(String taskId){
		// 先根据任务id拿出所有的bug
        ResultPage<SimpleBug> rp =  m_PsBug.search(ConditionUtil.eq(ConditionUtil.field("m_TaskId"), taskId));
        HashMap<String,Integer> map = new HashMap<>();
        for (SimpleBug simpleBug :  ResultPageHelper.toForeach(rp)) {
        	
        	//统计状态
        	
        	if(null ==  map.get("s"+simpleBug.getState().getName())) {
                //如果为当前状态名称的key下的value为空，代表第一次遍历到，给他设值为1
                map.put("s"+simpleBug.getState().getName(), 1);
        	}else {
                //如果不为null，代表不是第一次访问，将原来的值+1，再存回去
                int nums =  map.get("s"+simpleBug.getState().getName())+1;
                map.replace("s"+simpleBug.getState().getName(),nums);
        	}
        	
        	//统计测试人员
        	
        	List<String> testers =  simpleBug.getTester();
        	if(null != testers) {
        		//先取出测试人list，遍历该list
                for (int i = 0; i < testers.size();  i++) {
    	             if(null ==  map.get("t"+testers.get(i))) {
    	                  map.put("t"+testers.get(i), 1);
    	             }else {
    	                  int nums =  map.get("t"+testers.get(i))+1;
    	                  map.replace("t"+testers.get(i),  nums);
    	             }
                }
        	}
        	
            
            //统计处理人员
            
            List<String> handlers =  simpleBug.getHandler();
            if(null != handlers) {
            	//先取出处理人list，遍历该list
                for (int i = 0; i < handlers.size();  i++) {
                     if(null ==  map.get("h"+handlers.get(i))) {
                          map.put("h"+handlers.get(i), 1);
                     }else {
                          int nums =  map.get("h"+handlers.get(i))+1;
                          map.replace("h"+handlers.get(i),  nums);
                     }
                }
            }
            
        	
        }
        //统计bug总数
        map.put("bug总数", rp.getCount());
        //统计已完成的bug数量
        int finishedBug = 0;
        if(null !=  map.get(SimpleBug.STATE_SOLVE.getName())) {
            finishedBug +=  map.get(SimpleBug.STATE_SOLVE.getName());
        }
        
        if(null !=  map.get(SimpleBug.STATE_NO_UPDATE.getName())) {
            finishedBug +=  map.get(SimpleBug.STATE_NO_UPDATE.getName());
        }
        
        if(null !=  map.get(SimpleBug.STATE_CANT_SOLVE.getName())) {
            finishedBug +=  map.get(SimpleBug.STATE_CANT_SOLVE.getName());
        }
        map.put("已完成bug数", finishedBug);
        
        return map;
	}
}
